let listeningUrls = ["http://172.25.142.67/*", "https://testhrssc.mychery.com/*"];


let panelWindowId = null;

// 点击图标时创建/聚焦窗口
chrome.action.onClicked.addListener(async () => {
    if (panelWindowId) {
        // 如果窗口已存在则聚焦
        chrome.windows.update(panelWindowId, {focused: true});
    } else {
        // 创建新窗口
        const window = await chrome.windows.create({
            url: chrome.runtime.getURL("panel.html"),
            type: "popup",
            width: 800,
            height: 300,
            left: 420, // 右侧贴边
            top: 100
        });
        panelWindowId = window.id;

        // 监听窗口关闭
        chrome.windows.onRemoved.addListener((closedWindowId) => {
            if (closedWindowId === panelWindowId) panelWindowId = null;
        });
    }
});

// 其他原有监听请求头的代码保持不变

let capturedToken = null;
let requestsData = new Map();

// 监听所有网络请求
chrome.webRequest.onBeforeSendHeaders.addListener(
    (details) => {
        const type = details.type;
        if(type === "xmlhttprequest") {

            const requestId = details.requestId;
            const headers = details.requestHeaders;
            const authHeader = headers.find(
                h => h.name.toLowerCase() === "token" // 可修改为其他头如 "x-auth-token"
            );

            if (authHeader) {
                capturedToken = authHeader.value;
                chrome.storage.local.set({token: capturedToken});
            }

            requestsData.set(requestId, {
                url: details.url,
                method: details.method,
                requestHeaders: headers,
                type: type,
                response: null
            });
        }

    },
    {urls: listeningUrls},
    ["requestHeaders", "extraHeaders"]
);

chrome.webRequest.onCompleted.addListener(
    (details) => {
        // 捕获响应信息
        chrome.storage.local.set({
            requests: Array.from(requestsData.values()).slice(-50) // 保留最近50条
        });
    },
    {urls: listeningUrls}
);
